"use client";
import { ArrowLeft, Check, CheckCircle2, CheckIcon, Download, Edit, Import, LoaderCircle, Save, SeparatorVertical, Settings, Trash2, X } from "lucide-react"
import { Button } from "../components/ui/button"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "../components/ui/dropdown-menu"
import { Input } from "../components/ui/input"
import { useEffect, useState } from "react"
import { useToast } from "../components/ui/use-toast";
import { useRouter } from 'next/navigation';
import { addChatFlow, deleteChatFlow, updateChatFlow } from "@/server/flowise/data";
import { useDebouncedCallback } from "use-debounce";
import useReactflowStore from "@/lib/store/useReactflowStore";

export default function CanvasHeader({ data }: { data?: any }) {
    const [flowName, setFlowName] = useState<string>("");
    const [loading, setLoading] = useState<boolean>(false);
    const [isEdit, setIsEdit] = useState<boolean>(false);
    const router = useRouter();
    const { toast } = useToast();
    const reactflowStore = useReactflowStore();

    useEffect(() => {
        setFlowName(data?.name)
    }, [data?.name]);

    const goBack = () => {
        router.back();
    }

    const onSave = useDebouncedCallback(() => {
        const flowData = {
            nodes: reactflowStore.reactFlowInstance?.getNodes(),
            edges: reactflowStore.reactFlowInstance?.getEdges(),
            viewport: reactflowStore.reactFlowInstance?.getViewport()
        }
        let param: any = {
            id: data?.id,
            name: flowName,
            flowData: JSON.stringify(flowData),
        }
        setLoading(true);
        if (!param.id) {
            param = {
                ...param,
                deployed: false,
                isPublic: false,
                type: 'CHATFLOW',
            }
            addChatFlow(param).then(res => {
                if (res) {
                    toast({
                        className: 'bg-[#43a047] py-4',
                        title: (<div className="flex items-center gap-2 max-w-[300px] shadow-xl">
                            <CheckCircle2 className="w-5 h-5 text-white" />
                            <div className="text-base text-white">保存成功!</div>
                        </div> as any),
                    });
                    setIsEdit(false);
                } else {
                    toast({ title: '操作失败' })
                }
            }).finally(() => {
                // setLoading(false);
            });
            return;
        }
        updateChatFlow(param).then(res => {
            if (res) {
                toast({
                    className: 'bg-[#43a047] py-4',
                    title: (<div className="flex items-center gap-2 max-w-[300px] shadow-xl">
                        <CheckCircle2 className="w-5 h-5 text-white" />
                        <div className="text-base text-white">保存成功!</div>
                    </div> as any),
                });
                setIsEdit(false);
            } else {
                toast({ title: '操作失败' })
            }
        }).finally(() => {
            setLoading(false);
        });
    }, 100);

    const onImportFile = () => {
        const fileInput: any = document.getElementById('fileInput');
        fileInput?.click();
        fileInput.onchange = (event: any) => {
            const file = event.target.files[0];
            const reader: any = new FileReader();
            try {
                reader.onload = function () {
                    const flowData = JSON.parse(reader.result);
                    if (flowData) {
                        reactflowStore.reactFlowInstance?.setNodes(flowData.nodes)
                        reactflowStore.reactFlowInstance?.setEdges(flowData.edges)
                        reactflowStore.reactFlowInstance?.setViewport(flowData.viewport)
                    }
                };
                reader.readAsText(file);
            } catch {
                toast({ title: '导入失败' })
            }
        };
    }

    const onExportFile = () => {
        const flowData = {
            nodes: reactflowStore.reactFlowInstance?.getNodes(),
            edges: reactflowStore.reactFlowInstance?.getEdges(),
            viewport: reactflowStore.reactFlowInstance?.getViewport()
        }
        const json = JSON.stringify(flowData, null, 2);
        const blob = new Blob([json], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${data?.name || '未知'}.json`;
        a.click();
    }

    const onDelete = () => {
        deleteChatFlow(data?.id).then(res => {
            if (res?.affected === 1) {
                toast({
                    className: 'bg-[#43a047] py-4',
                    title: (<div className="flex items-center gap-2 max-w-[300px] shadow-xl">
                        <CheckCircle2 className="w-5 h-5 text-white" />
                        <div className="text-base text-white">删除成功!</div>
                    </div> as any),
                });
                router.back();
            } else {
                toast({ title: '操作失败' })
            }
        });
    }

    return <div className="flex items-center justify-between whitespace-nowrap border-b py-3 px-4 shadow-sm">
        <div className="flex items-center gap-2">
            <Button variant="outline" size="icon" className="rounded-xl mr-3" title="返回" onClick={goBack}>
                <ArrowLeft className="h-5 w-5 text-main" />
            </Button>
            {
                isEdit ?
                    <>
                        <div className="min-w-[80px]">
                            <Input placeholder="请输入" value={flowName} onChange={(e: any) => setFlowName(e.target.value)} />
                        </div>
                        <Button variant="outline" size="icon" className="rounded-xl" title="保存" onClick={onSave}>
                            <Check className="h-5 w-5 text-main" />
                        </Button>
                        <Button variant="outline" size="icon" className="rounded-xl" title="取消" onClick={() => setIsEdit(!isEdit)}>
                            <X className="h-5 w-5 text-secondary" />
                        </Button>
                    </> :
                    <>
                        <div className="min-w-[80px] text-gray-500">{flowName || '请输入名称'}</div>
                        <Button variant="outline" size="icon" className="rounded-xl" title="编辑" onClick={() => setIsEdit(!isEdit)}>
                            <Edit className="h-5 w-5 text-secondary" />
                        </Button>
                    </>
            }
        </div>
        <div className="flex items-center gap-2">
            <Button variant="outline" size="icon" className="rounded-xl" title="API配置">
                <SeparatorVertical className="h-5 w-5 text-main" />
            </Button>
            <Button variant="outline" size="icon" className="rounded-xl" title="保存" disabled={loading}>
                {
                    loading ? <LoaderCircle className="h-5 w-5 animate-spin" /> :
                        <Save className="h-5 w-5 text-secondary" onClick={() => onSave()} />
                }
            </Button>
            <DropdownMenu>
                <DropdownMenuTrigger asChild>
                    <Button variant="outline" size="icon" className="rounded-xl" title="设置">
                        <Settings className="h-5 w-5 text-gray-500" />
                    </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent className="mt-2">
                    <DropdownMenuItem onClick={onExportFile}>
                        <Download className="mr-2 h-4 w-4 text-gray-500" />
                        <span>导出</span>
                    </DropdownMenuItem>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem onClick={onImportFile}>
                        <input id="fileInput" type="file" accept=".json,application/json" className="sr-only" />
                        <Import className="mr-2 h-4 w-4 text-gray-500" />
                        <span>导入</span>
                    </DropdownMenuItem>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem onClick={onDelete}>
                        <Trash2 className="mr-2 h-4 w-4 text-gray-500" />
                        <span>删除</span>
                    </DropdownMenuItem>
                </DropdownMenuContent>
            </DropdownMenu>
        </div>
    </div>
}